extends Node3D

enum CameraMode { BATTLE_VIEW, OVERVIEW }

var current_mode: CameraMode = CameraMode.BATTLE_VIEW

@onready var camera: Camera3D = $Camera3D
@onready var ui_label = get_node("/root/Main/UI/DebugInfo/CameraModeLabel")

const CAMERA_SETTINGS = {
	CameraMode.BATTLE_VIEW: {
		"position": Vector3(0, 45, 30),
		"rotation_x": deg_to_rad(-50),
		"fov": 55,
		"name": "Battle View"
	},
	CameraMode.OVERVIEW: {
		"position": Vector3(0, 70, 40),
		"rotation_x": deg_to_rad(-55),
		"fov": 45,
		"name": "Overview Mode"
	}
}

var transition_speed: float = 2.0
var target_position: Vector3
var target_rotation: Vector3
var target_fov: float

func _ready():
	apply_camera_mode(current_mode)
	update_ui()

func _input(event):
	if event.is_action_pressed("camera_mode_1"):
		set_camera_mode(CameraMode.BATTLE_VIEW)
	elif event.is_action_pressed("camera_mode_2"):
		set_camera_mode(CameraMode.OVERVIEW)

func set_camera_mode(mode: CameraMode):
	if current_mode != mode:
		current_mode = mode
		apply_camera_mode(mode)
		update_ui()

func apply_camera_mode(mode: CameraMode):
	var settings = CAMERA_SETTINGS[mode]
	
	target_position = settings["position"]
	target_rotation = Vector3(settings["rotation_x"], 0, 0)
	target_fov = settings["fov"]
	
	position = target_position
	rotation = target_rotation
	camera.fov = target_fov

func _process(delta):
	if position != target_position:
		position = position.lerp(target_position, transition_speed * delta)
	if rotation != target_rotation:
		rotation = rotation.lerp(target_rotation, transition_speed * delta)
	if camera.fov != target_fov:
		camera.fov = lerp(camera.fov, target_fov, transition_speed * delta)

func update_ui():
	if ui_label:
		var mode_name = CAMERA_SETTINGS[current_mode]["name"]
		ui_label.text = "Camera Mode: " + mode_name + " (Press 1/2 to switch)"

func get_mouse_world_position(mouse_pos: Vector2) -> Vector3:
	var from = camera.project_ray_origin(mouse_pos)
	var to = from + camera.project_ray_normal(mouse_pos) * 1000
	
	var space_state = camera.get_world_3d().direct_space_state
	var ray_query = PhysicsRayQueryParameters3D.create(from, to)
	ray_query.collision_mask = 1
	var result = space_state.intersect_ray(ray_query)
	
	if result:
		return result.position
	return Vector3.ZERO
